package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author lijianguo
 * @Date 26/08/2024 11:11 pm
 * 请输入类的简介
 **/
public class MyMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        // createTime 这个字段与pojo类中字段对应
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        // 用户信息
        this.setFieldValByName("createBy", getUserName(), metaObject);
        this.setFieldValByName("updateBy", getUserName(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);

        // 用户信息
        this.setFieldValByName("updateBy", getUserName(), metaObject);
    }

    private LoginUser getLoginUser(){
        try {
            return SecurityUtils.getLoginUser();
        }catch (Exception e){
            return null;
        }
    }

    public String getUserName(){
        LoginUser loginUser = getLoginUser();
        if (loginUser == null){
            return null;
        }else {
            return String.valueOf(loginUser.getUser().getNickName());
        }
    }

    public String getUserId(){
        LoginUser loginUser = getLoginUser();
        if (loginUser == null){
            return null;
        }else {
            return String.valueOf(loginUser.getUser().getUserId());
        }
    }
}
